package com.my.lock.v25;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by Scarlett on 2018/9/13 0013.
 */
public class NonReentrantNonFairLock implements Lock {
    private static final Logger LOGGER = LoggerFactory.getLogger(NonReentrantNonFairLock.class);

    private Sync sync = new Sync();

    @Override
    public void lock() {
        this.sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        this.sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return this.sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return this.sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        this.sync.release(1);
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException("Not yet implemented!");
    }

    private static class Sync extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            return this.compareAndSetState(0, 1);
        }

        @Override
        protected boolean tryRelease(int arg) {
            this.setState(0);
            return true;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getState() == 0;
        }
    }


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        NonReentrantNonFairLock lock = new NonReentrantNonFairLock();

        for (int i = 0; i < 100; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        lock.lock();
                        LOGGER.info("locked by {}", Thread.currentThread().getName());
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }
    }
}
